/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.chart.Chart.CHART_URL = '../../../ext3/resources/charts.swf';
Ext.QuickTips.init();
var _pageSize = 20;
var _title = currentOrgName + ' 监测点月数据补采';
var store;
var now = new Date();
var saveServlet = '../../../servlet/data/YsjSave';
var loadServlet = '../../../servlet/data/YsjLoad';
var fieldName = ['name', 'shortName', 'pointType', 'pointType2', 'dataTime', 'voltageLevelName', 'maxVoltage', 'maxVoltageTime', 'minVoltage', 'minVoltageTime', 'avgVoltage',
    'defaultTotalTime', 'aboveUpperLimitMin', 'aboveUpperLimitNumber', 'underLowerLimitMin', 'underLowerLimitNumber', 'totalRunMin', 'rate', 'dataYear', 'dataMonth', 'dataDay',
    'id', 'isOffline', 'deviceId', 'pointId', 'type', 'status', 'reasonAnalyze', 'treatWay', 'completeCase', 'note', 'did'];
var fieldLabel = ['测点名称', '单位名称', '测点类别', '电网类别', '日期', '电压等级<br/>(kv)', '最高电压', '最高电压时间', '最低电压', '最低电压时间', '平均电压', '故障时间<br/>（分钟）',
    "超上限时间<br/>（分钟）", "超上限<br/>次数", "超下限时间<br/>（分钟）", "超下限<br/>次数", '总时间<br/>（分钟）', '合格率（%）', '年', '月', '日', 'ID', '在线离线', '设备ID', '监测点ID',
    '类型', '状态', '原因分析', '处理', '完成情况', '备注'];

var basic11 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '测点名称',
            name: 'name',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '单位名称',
            name: 'shortName',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic12 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '测点类别',
            name: 'pointType',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '电网类别',
            name: 'pointType2',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic13 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '电压等级(kv)',
            name: 'voltageLevelName',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '日期',
            id: 'DataYearMonth',
            name: 'dataYearMonth',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic1 = {
    xtype: 'fieldset',
    title: '基本信息',
    id: 'Basic1',
    autoHeight: true,
    layout: 'column',
    items: [basic11, basic12, basic13]
};


var basic21 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '最高电压',
            name: 'maxVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '最低电压',
            name: 'minVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '平均电压',
            name: 'avgVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '故障时间',
            name: 'defaultTotalTime',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '总时间',
            name: 'totalRunMin',
            anchor: '95%'
        }
    ]
};

var basic22 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'datefield',
            fieldLabel: '最高电压日期',
            id:'MaxVoltageDate',
            name: 'maxVoltageDate',            
            format: 'Y-m-d',
            anchor: '95%'
        },
        {
            xtype: 'datefield',
            fieldLabel: '最低电压日期',
            id:'MinVoltageDate',
            name: 'minVoltageDate',
            format: 'Y-m-d',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '超上限时间',
            name: 'aboveUpperLimitMin',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '超上限次数',
            name: 'aboveUpperLimitNumber',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '合格率（%）',
            id:'Rate',
            name: 'rate',
            anchor: '95%'
        }
    ]
};

var basic23 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'timefield',
            fieldLabel: '最高电压时间',
            id:'MaxVoltageTime',
            name: 'maxVoltageTime',
            format: 'H:i:s',
            anchor: '95%'
        },
        {
            xtype: 'timefield',
            fieldLabel: '最低电压时间',
            id:'MinVoltageTime',
            name: 'minVoltageTime',
            format: 'H:i:s',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '超下限时间',
            name: 'underLowerLimitMin',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '超下限次数',
            name: 'underLowerLimitNumber',
            anchor: '95%'
        }
    ]
};

var basic2 = {
    xtype: 'fieldset',
    title: '数据信息',
    id: 'Basic2',
    autoHeight: true,
    layout: 'column',
    items: [basic21, basic22, basic23]
};

var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [
                basic1, basic2
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };

                        var did = checkboxSel.getSelected().get('did');
                        var pointId = checkboxSel.getSelected().get('id');
                        var deviceId = checkboxSel.getSelected().get('deviceId');
                        var dataYear = Ext.getCmp('dateFrom').getValue().format('Y');
                        var dataMonth = Ext.getCmp('dateFrom').getValue().format('m');

                        if (did === null || did === '') {
                            submitConfig.params.pointId = pointId;
                            submitConfig.params.deviceId = deviceId;
                            submitConfig.params.dataYear = dataYear;
                            submitConfig.params.dataMonth = dataMonth;
                            submitConfig.params.cmd = 'create';
                        }
                        else {
                            submitConfig.params.id = did;
                            submitConfig.params.dataYear = dataYear;
                            submitConfig.params.dataMonth = dataMonth;
                            submitConfig.params.cmd = 'update';
                        }
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        Ext.getCmp('input-form').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);


var recallForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RecallForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskSave',
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesRecall',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    disable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winRecall.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {cmd: 'createYTask'}
                        };
                        //alert(checkboxSel.getSelections().length);
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.dates = beginDate;
                        Ext.getCmp('RecallForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winRecall.hide();
                    }
                }]
        }
);
var winRecall = new Ext.Window({
    title: _title,
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [recallForm]
});

function realRecall() {

}

function taskRecall() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，请选择需要补采的监测点");
    } else {
        //var r = checkboxSel.getSelected();
        var pointNames = getFields(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesRecall').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        winRecall.show();
    }
}

var recallAllForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RecallFormAll',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskSave',
            items: [
                {
                    fieldLabel: '数据年月',
                    xtype: 'datefield',
                    id: 'DateToF',
                    format: 'Y年m月',
                    width: 150,
                    value: now
                },
                {
                    id: 'HaveComboF',
                    xtype: 'havecombo'

                },
                {
                    id: 'ReportStatusComboF',
                    xtype: 'reportstatuscombo',
                    value: -1
                },
                {
                    id: 'RangeComboF',
                    xtype: 'rangecombo',
                    value: -1
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winRecallAll.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {cmd: 'createYAllTask'}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.dateTo = Ext.getCmp('DateToF').getValue().format('Ym');
                        submitConfig.params.have = Ext.getCmp('HaveComboF').getValue();
                        submitConfig.params.reportStatus = Ext.getCmp('ReportStatusComboF').getValue();
                        submitConfig.params.range = Ext.getCmp('RangeComboF').getValue();
                        Ext.getCmp('RecallFormAll').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winRecallAll.hide();
                    }
                }]
        }
);
var winRecallAll = new Ext.Window({
    title: '监测点月数据补采',
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [recallAllForm]
});

function taskRecallAll() {
    winRecallAll.show();
}

var win = new Ext.Window({
    layout: 'form',
    width: 680,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});


var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;

function manualRecall() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                modal: true,
                items: [inputForm]
            });
        }
        type = 2;
        var record = checkboxSel.getSelected();
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
        Ext.getCmp('DataYearMonth').setValue(Ext.getCmp('dateFrom').getValue().format('Y年m月'));
        
        var maxTime = record.get('maxVoltageTime');
        var minTime = record.get('minVoltageTime');
        
        var maxVoltageDate = Date.parseDate(maxTime,"Y-m-d H:i:s.u");
        var minVoltageDate = Date.parseDate(minTime,"Y-m-d H:i:s.u");
        Ext.getCmp("MaxVoltageDate").setValue(maxVoltageDate);
        Ext.getCmp("MinVoltageDate").setValue(minVoltageDate);
        
        Ext.getCmp("MaxVoltageTime").setValue(maxTime.substring(11,19));
        Ext.getCmp("MinVoltageTime").setValue(minTime.substring(11,19));
        
        var rate = record.get('rate');
        var rateFloat = parseFloat(rate);
        Ext.getCmp("Rate").setValue(rateFloat.toFixed(3));        
        
        win.setTitle('人工录入月数据');
        win.show();
    }
}


var beginDate = now.format('Ym');
var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName,
        autoLoad: true,
        baseParams: {cmd: 'recall', start: 0, limit: _pageSize, beginDate: now.format('Ym'), endDate: now.format('Ym')}
    });
    tbarPoint = new Ext.Toolbar({
        items: [
            pointTypeCombo, pointType2Combo, voltageLevelCombo, reportCombo, haveCombo
                    , pointText, searchButton
        ]
    });
    tbarPoint.insert(0, {
        xtype: 'datefield',
        id: 'dateFrom',
        format: 'Y年m月',
        width: 150,
        value: now,
        listeners: {
            select: function(c, date) {
                beginDate = date.format('Ym');
                store.baseParams.beginDate = beginDate;
                store.baseParams.endDate = beginDate;
            }
        }
    }
    );

    var grid = new Ext.grid.GridPanel({
        //title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            new Ext.grid.RowNumberer({width: 40, header: '序号'}),
            {header: 'PointId', dataIndex: 'pointId', hidden: true},
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0]},
            {header: fieldLabel[1], width: 80, sortable: true, dataIndex: fieldName[1]},
            {header: fieldLabel[2], width: 60, sortable: true, dataIndex: fieldName[2]},
            {header: '在线', width: 60, sortable: true, dataIndex: 'isOffline'},
            {header: fieldLabel[3], width: 60, sortable: true, dataIndex: fieldName[3]},
            {header: fieldLabel[5], width: 80, sortable: true, dataIndex: fieldName[5]},
            {header: fieldLabel[17], width: 100, sortable: true, align: 'right',format:'0.000',
                renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    var upper = record.get('aboveUpperLimitMin');
                    var lower = record.get('underLowerLimitMin');
                    var total = record.get('totalRunMin');
                    var rate = (1 - (parseInt(upper) + parseInt(lower)) / parseInt(total))*100;
                    
                    //alert(rate);
                    return rate.toFixed(3);
                }
            },
            {header: fieldLabel[6], width: 80, sortable: true, dataIndex: fieldName[6]},
            {header: fieldLabel[7], width: 100, sortable: true, dataIndex: fieldName[7]},
            {header: fieldLabel[8], width: 80, sortable: true, dataIndex: fieldName[8]},
            {header: fieldLabel[9], width: 100, sortable: true, dataIndex: fieldName[9]},
            {header: fieldLabel[10], width: 80, sortable: true, dataIndex: fieldName[10]},
            {header: fieldLabel[11], width: 80, sortable: true, dataIndex: fieldName[11]},
            {header: fieldLabel[12], width: 80, sortable: true, dataIndex: fieldName[12]},
            {header: fieldLabel[13], width: 50, sortable: true, dataIndex: fieldName[13]},
            {header: fieldLabel[14], width: 80, sortable: true, dataIndex: fieldName[14]},
            {header: fieldLabel[15], width: 50, sortable: true, dataIndex: fieldName[15]},
            {header: fieldLabel[16], width: 80, sortable: true, dataIndex: fieldName[16]}
        ],
        loadMask: true,
        tbar: new Ext.Toolbar([
            {
                text: '实时补采',
                iconCls: 'icon-daytime',
                handler: realRecall
                , style: {marginLeft: '10px'}
            },
            {
                text: '任务补采',
                iconCls: 'icon-linkratio',
                handler: taskRecall
            },
            {
                text: '全部补采',
                iconCls: 'icon-linkratio',
                handler: taskRecallAll
            },
            {
                text: '手工录入',
                iconCls: 'icon-linkratio',
                handler: manualRecall
            }
        ]),
        listeners: {
            'render': function() {
                tbarPoint.render(this.tbar);
            }
        },
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: '目前没有信息'
        })
    });

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);
